-- g_config 为全局变量,直接用

local cc_redis = {}

local rediscli = nil

cc_redis.init = function ()
    local redisObj = require "resty.redis"
    local redis = redisObj:new()

    redis:set_timeouts(1000, 1000, 1000) -- 1 sec
    local ok, err = redis:connect(g_config.redis_host, g_config.redis_port)
    if not ok then
        ngx.log( ngx.ERR, "redis connect failed: "..err)
        return
    end

    if g_config.redis_password ~= "" then
        local res, err = redis:auth(g_config.redis_password)
        if not res then
            ngx.log( ngx.ERR, "redis authenticate failed: "..err)
            return
        end
    end

    if g_config.redis_db_index > 0 then
        local ok, err = redis:select(g_config.redis_db_index)
        if not ok then
            ngx.log( ngx.ERR ,"redis SELECT DB failed: "..err)
            return
        end
    end
    
    rediscli = redis
end

cc_redis.set = function(key, value, timeout)
    local ok, _ = nil, nil
    if timeout > 0 then
        ok, _ = rediscli:setex(key, timeout, value)
        if not ok then
            ngx.log( ngx.ERR, "redis SETEX failed: "..err)
            return
        end
    else
        ok, _ = rediscli:set(key, value)
        if not ok then
            ngx.log( ngx.ERR, "redis SET failed: "..err)
            return
        end
    end
    return ok
end

cc_redis.incr = function(key)
    local ok, err = rediscli:incr(key)
    if not ok then
        ngx.log( ngx.ERR, "redis INCR failed: "..err)
        return
    end
    return ok
end

cc_redis.get = function(key)
    local res, err = rediscli:get(key)
    if not res then
        ngx.log( ngx.ERR, "redis GET failed: "..err)
        return
    end

    if res == ngx.null then
        -- not found
        -- ngx.log( ngx.ERR, "redis GET not found ")
        return
    end
    return res
end

cc_redis.set_ip = function(ip, timeout)
    local ipkey = g_ccip_prefix..ip
    local ok, _ = nil, nil
    if timeout > 0 then
        ok, _ = rediscli:setex(ipkey, timeout, 1)
        if not ok then
            ngx.log( ngx.ERR, "redis SETEX failed: "..err)
            return
        end
    else
        ok, _ = rediscli:set(ipkey, 1)
        if not ok then
            ngx.log( ngx.ERR, "redis SET failed: "..err)
            return
        end
    end
    return ok
end

cc_redis.ip_exist = function(ip)
    local ipkey = g_ccip_prefix..ip
    local res, err = rediscli:get(ipkey)
    if not res then
        ngx.log( ngx.ERR, "redis GET failed: ", err)
        return false
    end

    if res == ngx.null then
        -- not found
        return false
    end

    return true
end

cc_redis.clean_all_ccip = function()
    local all_keys = rediscli:keys(g_ccip_prefix..'*')
    for _, key in pairs(all_keys) do
        rediscli:del(key)
    end
end

return cc_redis
